<template>
	<view class="auth-container">
		<!-- 认证状态卡片 -->
		<view class="status-card">
			<view class="status-header">
				<view class="status-icon" :class="statusInfo.iconClass">
					<text class="status-emoji">{{ statusInfo.emoji }}</text>
				</view>
				<view class="status-content">
					<text class="status-title">{{ statusInfo.title }}</text>
					<text class="status-desc">{{ statusInfo.desc }}</text>
				</view>
			</view>
		</view>

		<!-- 认证表单 -->
		<view v-if="authStatus === 'none' || authStatus === 'rejected'" class="auth-form">
			<view class="form-section">
				<text class="section-title">基本信息</text>

				<view class="form-item">
					<text class="form-label">
						<text class="label-text">真实姓名</text>
						<text class="required">*</text>
					</text>
					<input class="form-input" v-model="formData.realname" placeholder="请输入真实姓名" maxlength="20" />
				</view>

				<view class="form-item">
					<text class="form-label">
						<text class="label-text">身份证号</text>
						<text class="required">*</text>
					</text>
					<input class="form-input" v-model="formData.idcard" placeholder="请输入身份证号码" maxlength="18"
						@change="setBirthday" />
				</view>

				<view class="form-item">
					<text class="form-label">
						<text class="label-text">出生日期</text>
						<text class="required">*</text>
					</text>
					<input class="form-input" v-model="formData.birthday" placeholder="请输入身份证号码" disabled />
				</view>

				<view v-if="userInfo.mobile && userInfo.mobile!==''" class="form-item">
					<text class="form-label">当前手机号</text>
					<text class="current-phone">{{ userInfo.mobile_hidden }}</text>
				</view>
				<view v-else class="form-item">
					<text class="form-label">
						<text class="label-text">手机号码</text>
						<text class="required">*</text>
					</text>
					<input class="form-input" v-model="formData.mobile" placeholder="请输入手机号码" type="number"
						maxlength="11" />
				</view>

				<view class="form-item">
					<text class="form-label">
						<text class="label-text">验证码</text>
						<text class="required">*</text>
					</text>
					<view class="verify-code-wrapper">
						<input class="verify-input" v-model="verifyCode" placeholder="请输入6位验证码" type="number"
							maxlength="6" />
						<view class="verify-btn" :class="{ disabled: countdown > 0 }" @click="sendVerifyCode">
							<text class="verify-btn-text">{{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}</text>
						</view>
					</view>
				</view>

			</view>

			<view class="form-section">
				<text class="section-title">
					<text class="label-text">身份证照片</text>
					<text class="required">*</text>
				</text>

				<view class="upload-section">
					<view class="upload-item">
						<text class="upload-label">身份证正面</text>
						<view class="upload-area" @click="uploadIdCardFront">
							<image v-if="formData.idcard_image1" :src="$tools.buildUrl(formData.idcard_image1)"
								class="upload-image" mode="aspectFill" />
							<view v-else class="upload-placeholder">
								<text class="upload-icon">📷</text>
								<text class="upload-text">点击上传</text>
							</view>
						</view>
					</view>

					<view class="upload-item">
						<text class="upload-label">身份证反面</text>
						<view class="upload-area" @click="uploadIdCardBack">
							<image v-if="formData.idcard_image2" :src="$tools.buildUrl(formData.idcard_image2)"
								class="upload-image" mode="aspectFill" />
							<view v-else class="upload-placeholder">
								<text class="upload-icon">📷</text>
								<text class="upload-text">点击上传</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view class="agreement-section">
				<view class="agreement-item" @click="toggleAgreement">
					<view class="checkbox" :class="{ checked: agreedToTerms }">
						<text v-if="agreedToTerms" class="check-icon">✓</text>
					</view>
					<text class="agreement-text">我已阅读并同意</text>
					<text class="agreement-link" @click.stop="viewAgreement">《分销员协议》</text>
				</view>
			</view>

			<button class="submit-btn" @click="submitAuth" :disabled="!canSubmit">
				提交认证申请
			</button>
		</view>

		<!-- 审核中状态 -->
		<view v-if="authStatus === 'pending'" class="pending-info">
			<view class="info-item">
				<text class="info-label">申请时间：</text>
				<text class="info-value">{{ authInfo.applyTime }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">预计审核时间：</text>
				<text class="info-value">1-3个工作日</text>
			</view>
		</view>

		<!-- 已通过状态 -->
		<view v-if="authStatus === 'approved'" class="approved-info">
			<view class="info-item">
				<text class="info-label">认证时间：</text>
				<text class="info-value">{{ authInfo.approveTime }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">分销员等级：</text>
				<text class="info-value">{{ authInfo.level }}</text>
			</view>
			<button class="action-btn" @click="toDistributionCenter">
				进入分销中心
			</button>
		</view>

		<!-- 被拒绝状态 -->
		<view v-if="authStatus === 'rejected'" class="rejected-info">
			<view class="info-item">
				<text class="info-label">拒绝原因：</text>
				<text class="info-value">{{ authInfo.rejectReason }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">拒绝时间：</text>
				<text class="info-value">{{ authInfo.rejectTime }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import {
		maskPhone,
		maskIdCard,
		validatePhone,
		validateVerifyCode
	} from '@/common/validate.js'
	import projectConfig from '@/common/config.js';

	export default {
		data() {
			return {
				// 认证状态：none-未申请, pending-审核中, approved-已通过, rejected-已拒绝
				authStatus: 'none',
				// 认证信息
				authInfo: {
					applyTime: '',
					approveTime: '',
					rejectTime: '',
					rejectReason: '',
					level: 'D级分销员'
				},
				// 表单数据
				formData: {
					realname: '',
					mobile: '',
					idcard: '',
					birthday: '',
					idcard_image1: '',
					idcard_image2: ''
				},
				verifyCode: '',
				countdown: 0,
				loading: false,
				// 是否同意协议
				agreedToTerms: false
			}
		},
		computed: {
			...mapGetters(['isLogin', 'userInfo']),

			// 状态信息
			statusInfo() {
				const statusMap = {
					none: {
						title: '分销员认证',
						desc: '完成实名认证，成为分销员',
						emoji: '🆔',
						iconClass: 'status-default'
					},
					pending: {
						title: '审核中',
						desc: '您的认证申请正在审核中，请耐心等待',
						emoji: '⏳',
						iconClass: 'status-pending'
					},
					approved: {
						title: '认证成功',
						desc: '恭喜您成为分销员，可以开始分销业务',
						emoji: '✅',
						iconClass: 'status-success'
					},
					rejected: {
						title: '认证失败',
						desc: '很抱歉，您的认证申请未通过，可重新申请',
						emoji: '❌',
						iconClass: 'status-error'
					}
				}
				return statusMap[this.authStatus] || statusMap.none
			},
			// 是否可以提交
			canSubmit() {
				return this.formData.realname &&
					this.formData.idcard &&
					this.formData.mobile &&
					this.formData.idcard_image1 &&
					this.formData.idcard_image2 &&
					this.verifyCode &&
					this.verifyCode.length === 6 &&
					this.agreedToTerms
			}
		},
		onLoad() {
			this.formData.mobile = this.$secret.decryptAES(this.userInfo.mobile);
			this.checkAuthStatus()
		},
		methods: {
			// 检查认证状态
			checkAuthStatus() {
				// 审核状态：-1待审核 0未审核 1审核中 2审核通过 3驳回
				this.$api.user.GetUserExtInfo4().then(res => {
					const info = res.data.userLevel
					if (info.check_status === 2) {
						this.authStatus = 'approved'
						this.authInfo.approveTime = info.last_level_time || info.last_check_time
						this.authInfo.level = info.user_level_desc || '初级分销员'
					} else if (info.check_status === 3) {
						this.authStatus = 'rejected'
						this.authInfo.rejectTime = info.last_check_time
						this.authInfo.rejectReason = info.last_check_reason
					} else if (info.check_status === 0) {
						this.authStatus = 'none'
					} else if (info.check_status < 2) {
						this.authStatus = 'pending'
						this.authInfo.applyTime = info.submit_check_time
					}
				});
			},

			// 上传身份证正面
			uploadIdCardFront() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (res) => {
						this.uploadPhoto('idcard_image1', res.tempFilePaths[0]);
					}
				})
			},

			// 上传身份证反面
			uploadIdCardBack() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (res) => {
						this.uploadPhoto('idcard_image2', res.tempFilePaths[0]);
					}
				})
			},

			// 上传图片到服务器
			uploadPhoto(propertyName, tempFilePath) {
				uni.showLoading({
					title: '正在上传'
				})
				const uploadUrl = '/api/App_Upload/UploadFile';
				const headerConfig = this.$sign.buildHeaderSign(uploadUrl, this.userInfo, {}, 'POST'); // 生成签名
				//上传到服务器
				uni.uploadFile({
					url: projectConfig.baseUrl + uploadUrl,
					filePath: tempFilePath, //要上传文件资源的路径 (本地路径)
					name: 'photo', //文件对应的 key，开发者在服务端可以通过这个 key 获取文件的二进制内容
					header: headerConfig,
					formData: {}, //HTTP 请求中其他额外的 form data       
					success: res => {
						uni.hideLoading()
						var jsonObj = this.$tools.parseJsonObject(res.data)
						if (jsonObj.code == 100) {
							//保存成功 
							this.formData[propertyName] = jsonObj.data.relativeUrl
						} else {
							//保存失败
							uni.showToast({
								title: jsonObj.msg,
								icon: 'error'
							})
						}
					},
					fail: err => {
						uni.hideLoading()
						uni.showToast({
							title: '上传图片错误：' + JSON.stringify(err),
							icon: 'error'
						})
					}
				})
			},

			// 验证手机号格式
			isValidPhone(phone) {
				return validatePhone(phone)
			},

			// 发送验证码
			async sendVerifyCode() {
				if (this.countdown > 0 || !this.isValidPhone(this.formData.mobile)) {
					if (!this.isValidPhone(this.formData.mobile)) {
						uni.showToast({
							title: '请输入正确的手机号',
							icon: 'none'
						})
					}
					return
				}

				if (this.userInfo.mobile && this.userInfo.mobile !== '') {
					this.$api.user.GetVerifyCode({
						mobile: this.formData.mobile
					}).then(res => {
						uni.showToast({
							title: '验证码已发送',
							icon: 'success'
						})

						this.startCountdown()
					})
				} else {
					this.$api.user.GetVerifyCode2({
						mobile: this.formData.mobile
					}).then(res => {
						uni.showToast({
							title: '验证码已发送',
							icon: 'success'
						})

						this.startCountdown()
					})
				}

			},

			// 开始倒计时
			startCountdown() {
				this.countdown = 60
				const timer = setInterval(() => {
					this.countdown--
					if (this.countdown <= 0) {
						clearInterval(timer)
					}
				}, 1000)
			},

			// 切换协议同意状态
			toggleAgreement() {
				this.agreedToTerms = !this.agreedToTerms
			},

			// 查看协议
			viewAgreement() {
				uni.navigateTo({
					url: '/fenxiao-package/distribution/agreement'
				})
			},

			// 提交认证申请
			submitAuth() {
				if (!this.canSubmit || this.loading) {
					uni.showToast({
						title: '请完善所有必填信息',
						icon: 'none'
					})
					return
				}

				// 验证身份证号格式
				if (!this.validateIdCard(this.formData.idcard)) {
					uni.showToast({
						title: '身份证号格式不正确',
						icon: 'none'
					})
					return
				}

				// 验证手机号格式
				if (!this.validatePhone(this.formData.mobile)) {
					uni.showToast({
						title: '手机号格式不正确',
						icon: 'none'
					})
					return
				}

				uni.showLoading({
					title: '提交中...'
				})

				this.loading = true

				this.$api.user.updateUserBaseInfo({
					info: this.formData,
					verifyMobile: this.formData.mobile,
					captcha: this.verifyCode
				}).then(res => {
					this.loading = false
					this.userInfo.realname = this.formData.realname;
					this.userInfo.idcard_hidden = maskIdCard(this.formData.idcard);
					this.userInfo.mobile = this.$secret.encryptAES(this.formData.mobile);
					this.userInfo.mobile_hidden = maskPhone(this.formData.mobile);
					this.userInfo.check_status = -1;
					this.$store.dispatch('updateUserInfo', this.userInfo);
					uni.hideLoading()
					uni.showToast({
						title: res.msg,
						icon: 'success'
					})
					this.authStatus = 'pending'
					this.authInfo.applyTime = this.getCurrentTime()
				}).catch(error => {
					this.loading = false
					uni.hideLoading()
					uni.showToast({
						title: error.message || '修改失败，请重试',
						icon: 'none'
					})
				});
			},

			// 验证身份证号
			validateIdCard(idCard) {
				const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
				return reg.test(idCard)
			},

			// 验证手机号
			validatePhone(phone) {
				const reg = /^1[3-9]\d{9}$/
				return reg.test(phone)
			},

			// 获取当前时间
			getCurrentTime() {
				const now = new Date()
				return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
			},

			// 跳转到分销中心
			toDistributionCenter() {
				uni.navigateBack()
			},

			setBirthday() {
				this.formData.birthday = this.getBirthdayFromIdCard(this.formData.idcard);
			},

			getBirthdayFromIdCard(idCard) {
				// 验证身份证长度（15位或18位）
				if (!/^\d{15}$|^\d{17}[\dXx]$/.test(idCard)) {
					throw new Error('无效的身份证号码');
				}

				let year, month, day;

				// 处理15位身份证
				if (idCard.length === 15) {
					year = '19' + idCard.substr(6, 2); // 7-8位：年份（补19前缀）
					month = idCard.substr(8, 2); // 9-10位：月份
					day = idCard.substr(10, 2); // 11-12位：日期
				}
				// 处理18位身份证
				else {
					year = idCard.substr(6, 4); // 7-10位：年份
					month = idCard.substr(10, 2); // 11-12位：月份
					day = idCard.substr(12, 2); // 13-14位：日期
				}

				// 返回标准日期格式
				return `${year}-${month}-${day}`;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.auth-container {
		background-color: #f8f9fa;
		min-height: 100vh;
		padding: 20rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	}

	/* 状态卡片 */
	.status-card {
		background-color: white;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.status-header {
		display: flex;
		align-items: center;
	}

	.status-icon {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 30rpx;
	}

	.status-default {
		background-color: #f8f9fa;
	}

	.status-pending {
		background-color: #fff3cd;
	}

	.status-success {
		background-color: #d4edda;
	}

	.status-error {
		background-color: #f8d7da;
	}

	.status-emoji {
		font-size: 36rpx;
	}

	.status-content {
		flex: 1;
	}

	.status-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 8rpx;
		display: block;
	}

	.status-desc {
		font-size: 26rpx;
		color: #666;
	}

	/* 表单样式 */
	.auth-form {
		background-color: white;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.form-section {
		margin-bottom: 40rpx;
	}

	.form-section:last-child {
		margin-bottom: 0;
	}

	.section-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
		display: block;
	}

	.form-item {
		margin-bottom: 30rpx;
	}

	.form-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
		display: block;
	}

	.form-input {
		width: 100%;
		height: 80rpx;
		border: 2rpx solid #e9ecef;
		border-radius: 12rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		color: #333;
		box-sizing: border-box;
	}

	.form-input:focus {
		border-color: #52a58a;
	}


	/* 上传区域 */
	.upload-section {
		display: flex;
		gap: 30rpx;
	}

	.upload-item {
		flex: 1;
	}

	.upload-label {
		font-size: 26rpx;
		color: #666;
		margin-bottom: 16rpx;
		display: block;
	}

	.upload-area {
		width: 100%;
		height: 200rpx;
		border: 2rpx dashed #ddd;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
	}

	.upload-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.upload-placeholder {
		display: flex;
		flex-direction: column;
		align-items: center;
		color: #999;
	}

	.upload-icon {
		font-size: 48rpx;
		margin-bottom: 10rpx;
	}

	.upload-text {
		font-size: 24rpx;
	}

	/* 协议区域 */
	.agreement-section {
		margin: 40rpx 0;
	}

	.agreement-item {
		display: flex;
		align-items: center;
	}

	.checkbox {
		width: 32rpx;
		height: 32rpx;
		border: 2rpx solid #ddd;
		border-radius: 6rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 16rpx;
	}

	.checkbox.checked {
		background-color: #52a58a;
		border-color: #52a58a;
	}

	.check-icon {
		color: white;
		font-size: 20rpx;
	}

	.agreement-text {
		font-size: 26rpx;
		color: #666;
	}

	.agreement-link {
		font-size: 26rpx;
		color: #52a58a;
		text-decoration: underline;
	}

	/* 按钮样式 */
	.submit-btn {
		width: 100%;
		height: 88rpx;
		background-color: #52a58a;
		color: white;
		border: none;
		border-radius: 44rpx;
		font-size: 32rpx;
		font-weight: bold;
	}

	.submit-btn:disabled {
		background-color: #ccc;
	}

	.action-btn {
		width: 100%;
		height: 80rpx;
		background-color: #52a58a;
		color: white;
		border: none;
		border-radius: 40rpx;
		font-size: 28rpx;
		margin-top: 30rpx;
	}

	/* 信息展示 */
	.pending-info,
	.approved-info,
	.rejected-info {
		background-color: white;
		border-radius: 16rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.info-item {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.info-item:last-child {
		margin-bottom: 0;
	}

	.info-label {
		font-size: 28rpx;
		color: #666;
		min-width: 200rpx;
	}

	.info-value {
		font-size: 28rpx;
		color: #333;
		flex: 1;
	}

	/* 手机验证码 */
	.form-label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 15rpx;
		font-weight: 500;
	}

	.current-phone {
		font-size: 32rpx;
		color: #52a58a;
		font-weight: bold;
	}

	.form-input {
		width: 100%;
		height: 88rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 12rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		background-color: #fff;
	}

	.form-input:focus {
		border-color: #52a58a;
	}

	.verify-code-wrapper {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.verify-input {
		flex: 1;
		height: 88rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 12rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		background-color: #fff;
	}

	.verify-input:focus {
		border-color: #52a58a;
	}

	.verify-btn {
		width: 200rpx;
		height: 88rpx;
		background-color: #52a58a;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
	}

	.verify-btn.disabled {
		background-color: #e5e5e5;
		cursor: not-allowed;
	}

	.verify-btn-text {
		color: white;
		font-size: 26rpx;
	}

	.verify-btn.disabled .verify-btn-text {
		color: #999;
	}

	.tips-section {
		background-color: white;
		border-radius: 16rpx;
		padding: 30rpx;
	}

	.tips-title {
		display: block;
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}

	.tips-text {
		display: block;
		font-size: 26rpx;
		color: #666;
		line-height: 1.6;
		margin-bottom: 10rpx;
	}

	.tips-text:last-child {
		margin-bottom: 0;
	}

	.required {
		color: #ff4757;
		margin-left: 8rpx;
	}
</style>